<?php
class Admin_Model_Group extends Zend_Db_Table{
	protected $_name = 'user_group';
	protected $_primary = 'id';
	
	public function itemInSelectbox($arrParam = null, $option = null){
		$db = Zend_Registry::get('connectDb');
		if($option == null){
			$select = $db->select()
						 ->from('user_group', array('id', 'group_name'));
			$result = $db->fetchPairs($select);
			$result[0] = ' -- Select an Item -- ';
			ksort($result);
		}
		
		return $result;
	}
	
	public function countItem($arrParam = null, $option = null){
		$db = Zend_Registry::get('connectDb');
		//$db = Zend_Db::factory($adapter, $config);
		$ssFilter = $arrParam['ssFilter'];
		
		$select = $db->select()
					 ->from('user_group AS g', array('COUNT(g.id) AS totalItem'));
		if(!empty($ssFilter['keywords'])){
			$keywords = '%' . $ssFilter['keywords'] . '%';
			$select->where('g.group_name LIKE ?', $keywords); // doi so thu 3 ep kieu STRING
		}
		
		$result = $db->fetchOne($select);
		return $result;
	}
	
	public function listItem($arrParam = null, $option = null){
		$db = Zend_Registry::get('connectDb');
		//$db = Zend_Db::factory($adapter, $config);
		$paginator = $arrParam['paginator'];
		$ssFilter = $arrParam['ssFilter'];
		
		if($option['task'] == 'admin-list'){
			$select = $db->select()
						 ->from('user_group AS g', array('id', 'group_name', 'group_acp', 'status', 'order'))
						 ->joinLeft('user AS u', 'g.id = u.group_id', 'COUNT(u.userid) AS members')
						 ->group('g.id');
			
			if(!empty($ssFilter['col']) && !empty($ssFilter['order'])){
				$select->order($ssFilter['col'] . ' ' . $ssFilter['order']);
			}
			
			
			if($paginator['itemCountPerPage']>0){
				$page = $paginator['currentPage'];
				$rowCount = $paginator['itemCountPerPage'];
				$select->limitPage($page, $rowCount);
			}
			if(!empty($ssFilter['keywords'])){
				$keywords = '%' . $ssFilter['keywords'] . '%';
				$select->where('g.group_name LIKE ?', $keywords); // doi so thu 3 ep kieu STRING
			}
			
			$result = $db->fetchAll($select);
		}
		
		return $result;
	}
        
        public function insertToPermission($groupId, $uid){
            $db                 = Zend_Registry::get('connectDb');
            $select             = $db->select()
                                     ->from('page AS p', array('id'));
            $pageIds            = $db->fetchAll($select);
            
            if (count($pageIds) > 0){
                foreach ($pageIds as $id) {
                    $this->insertPermission($db, $groupId, $id['id'], $uid);
                }
            }
                
        }
        
        public function updatePermission($db, $arrId, $column){
            $arr            = "('" .implode("','", $arrId) . "')";
            
            $update         = " UPDATE permission 
                                SET $column = '1', uidupdated = 'admin', dateupdated = NOW()   
                                WHERE id IN $arr  ";
//            echo $update; die();
            $db->query($update);
        }
        
        public function insertPermission($db, $groupId, $pageId, $uid){
            $update         = " INSERT INTO `permission` (`groupid`, `pageid`, `view_p`, `add_p`, `edit_p`, `delete_p`, `uidcreated`, `datecreated`) 
                                VALUES ('$groupId', '$pageId', '0', '0', '0', '0', '$uid', NOW() ); ";
//            echo $update; die();
            $db->query($update);
        }
	
	public function saveItem($arrParam = null, $option = null){
		
		if($option['task'] == 'admin-add'){
			$row                    = $this->fetchNew();
			$row->group_name 	= $arrParam['group_name'];
			$row->avatar 		= $arrParam['avatar'];
			$row->ranking 		= $arrParam['ranking'];
			$row->group_acp 	= $arrParam['group_acp'];
			$row->group_default = $arrParam['default'];
			$row->created 		= date("Y-m-d");
			$row->created_by 	= $arrParam['userinfor']['username'];
			$row->status 		= $arrParam['status'];
			$row->order 		= $arrParam['order'];
			
			$row->save();
                        $id                     = $row->id;
                        $this->insertToPermission($id, $arrParam['userinfor']['username']);
		}
		if($option['task'] == 'admin-edit'){
			$where = 'id = ' . $arrParam['id'];
			$row = $this->fetchRow($where);
			$row->group_name 	= $arrParam['group_name'];
			$row->avatar 		= $arrParam['avatar'];
			$row->ranking 		= $arrParam['ranking'];
			$row->group_acp 	= $arrParam['group_acp'];
			$row->group_default = $arrParam['default'];
			$row->modified 		= date("Y-m-d");
			$row->modified_by 	= $arrParam['userinfor']['username'];
			$row->status 		= $arrParam['status'];
			$row->order 		= $arrParam['order'];
				
			$row->save();
		}
                if ($option['task'] == 'permission'){
//                    echo "<pre>"; print_r($arrParam); die();
                    $id                 = $arrParam['id'];
                    $db                 = Zend_Registry::get('connectDb');
                    $update             = " UPDATE permission 
                                            SET uidupdated = 'admin', dateupdated = NOW(),
                                            view_p = '0', add_p = '0', edit_p = '0', delete_p = '0' 
                                            WHERE groupid = '$id' ";
                    $db->query($update);
                    
                    $arrView            = (isset($arrParam['view_p'])) ? $arrParam['view_p'] : array();
                    $arrAdd             = (isset($arrParam['add_p'])) ? $arrParam['add_p'] : array();
                    $arrEdit            = (isset($arrParam['edit_p'])) ? $arrParam['edit_p'] : array();
                    $arrDelete          = (isset($arrParam['delete_p'])) ? $arrParam['delete_p'] : array();
                    //update permission
                    if (count($arrView) > 0){
                        $this->updatePermission($db, $arrView, 'view_p');
                    }
                    if (count($arrAdd) > 0){
                        $this->updatePermission($db, $arrAdd, 'add_p');
                    }
                    if (count($arrEdit) > 0){
                        $this->updatePermission($db, $arrEdit, 'edit_p');
                    }
                    if (count($arrDelete) > 0){
                        $this->updatePermission($db, $arrDelete, 'delete_p');
                    }
                }
	}
	
        
	public function getItem($arrParam = null, $option = null){
		
		if($option['task'] == 'admin-info' || $option['task'] == 'admin-edit'){
			$where = 'id = ' . $arrParam['id'];
			$result = $this->fetchRow($where)->toArray();
		}
		
		return $result;
	}
        
        public function getListPermission($arrParam = null){
//            echo "<pre>"; print_r($arrParam); die();
            $db                 = Zend_Registry::get('connectDb');
            $id                 = $arrParam['id'];
            $select             = $db->select()
                                     ->from('permission AS p', array('p.id AS id', 'p.view_p AS view_p', 'p.add_p AS add_p',
                                         'p.edit_p AS edit_p', 'p.delete_p AS delete_p',
                                         'p.uidcreated AS uidcreated', 'p.datecreated AS datecreated',
                                         'p.uidupdated AS uidupdated', 'p.dateupdated AS dateupdated'))
                                     ->joinLeft('page AS pa', 'pa.id = p.pageid',array('pa.title AS title', 'pa.controller AS controller'))
                                     ->where("p.groupid = '$id'");
//            echo $select; die();
            $rs                 = $db->fetchAll($select);
            
            return $rs;
            
        }
	
	public function deleteItem($arrParam = null, $option = null){
		
		if($option['task'] == 'admin-delete'){
			$where = 'id = ' .$arrParam['id'];
			$this->delete($where);
		}
		
		if($option['task'] == 'admin-multi-delete'){
			$cid = $arrParam['cid'];
			if(count($cid)>0){
				if($arrParam['type'] == 1){
					$status = 1;
				}else{
					$status = 0;
				}
				$ids = implode(',', $cid);
				$where = 'id IN (' . $ids . ')';
				$this->delete($where);
			}
		}
	}
	
	public function changeStatua($arrParam = null, $option = null){
		$cid = $arrParam['cid'];
		if(count($cid)>0){
			if($arrParam['type'] == 1){
				$status = 1;
			}else{
				$status = 0;
			}
			$ids = implode(',', $cid);
			$data = array('status'=>$status);
			$where = 'id IN (' . $ids . ')';
			$this->update($data, $where);
			// UPDATE FROM user_group SET status = 1 WHERE id IN (1,2,3)
		}
		if($arrParam['id']>0){
			if($arrParam['type'] == 1){
				$status = 1;
			}else{
				$status = 0;
			}
			
			$data = array('status'=>$status);
			$where = 'id = ' . $arrParam['id'];
			$this->update($data, $where);
		}
	}
	
	public function changeAcp($arrParam = null, $option = null){
		if($arrParam['id']>0){
			if($arrParam['type'] == 1){
				$statusAcp = 1;
			}else{
				$statusAcp = 0;
			}
				
			$data = array('group_acp'=>$statusAcp);
			$where = 'id = ' . $arrParam['id'];
			$this->update($data, $where);
		}
	}
	
	public function sortItem($arrParam = null, $option = null){
		$cid = $arrParam['cid'];
		$order = $arrParam['order'];
		if(count($cid)>0){
			foreach($cid as $key=>$val){
				$data = array('order'=>$order[$val]);
				$where = 'id = ' . $val['cid'];
				$this->update($data, $where);
			}
		}
	}
}